/**
 * Copyright 2013 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Upload.js
 * @path:   js-src/upload/
 * @desc:   基于HTML5的上传的核心组件，基于奇传的接口
 *
 * @author: lichunping@qiyi.com
 * @date:   2013-05-15
 *
 */
qui(function(require, exports, module) {


    ///import js-src/lib/
    ///import js-src/com/

    Ancestor.Upload = function(options) {
        this.dao = Ancestor.Dao;
        this.config = Ancestor.Config;
        options = options || {};

        this.options = $.extend(true, {

            // 如果想支持想支持多文件需在外再封装一层
            file: null,

            uploadHost: null,
            // finishUrl: '/upload',
            // cancelUrl: '/cancelupload',

            requestURL: this.config.QICHUAN.image_requestURL_test,
            uploadURL: this.config.QICHUAN.image_uploadURL_test,

            deviceId: this.config.QICHUAN.deviceId,

            // 开始时间
            startTime: 0,

            role: 'epg_image',
            businessType: 'image',
            producttype: 'ppc',

            // spath: null,
            currentDate: null,
            // openAuthInfo: null,

            // 请求文件完成
            onRequest: function(data) {},
            // 开始发送数据
            onStart: function(data) {},
            // 上传成功
            onFinish: function(data) {},
            // 上传暂停
            onPause: function(data) {},
            // 上传恢复
            onResume: function(data) {},
            // 上传过程回调，每个分片
            onProgress: function(data) {},
            // 取消上传
            onCancel: function(data) {},
            // 上传失败
            onFail: function(data) {},
            // 上传出现错误
            onError: function(data) {}

        }, options);

        // 模拟构造方法，在实例化执行
        // 根据自己的需要加入需要初始化执行的内容
        this.construct = options.construct || function() {
            this.init();
        };

        // 放在最下方立即执行
        this.construct.call(this);
    };

    Ancestor.Upload.prototype = {

        init: function() {
            var self = this;
            var _options = self.options;

            /*
            var isNormalUser = User.Util.isNormal();
            if(!_options.uploadURL) {
                if(isNormalUser) {
                    _options.uploadURL = this.config.QICHUAN.image_uploadURL;
                } else {
                    _options.uploadURL = this.config.QICHUAN.inner_image_uploadURL;
                }
            }
            */
        },

        /**
         * 用于更新options内容，继承选项，覆盖相同属性
         * @param {Object} options  选项
         */
        update: function(options) {
            this.options = $.extend(true, this.options, options);
        },

        getUID: function() {
            return Com.string.createUUID();
        },

        getFile: function() {
            return this.options.file;
        },

        getUploadHost: function(url) {
            var self = this;
            if (this.uploadHost) {
                return this.uploadHost;
            }
            url = url || self.options.uploadUrl;
            if (!url || url.length <= 0) {
                return null;
            }
            // 含http://, 不是 Com.url.host(url);
            return url.substr(0, url.lastIndexOf('/'));
        },

        getFileType: function(name) {
            return Com.file.getFileType(name);
        },


        getDeviceId: function() {
            return this.options.deviceId;
        },

        getFilePath: function() {
            return this.options.role + this.options.spath;
        },


        getRequestFileOptions: function(options) {
            var self = this;
            var _options = self.options;
            options = options || {};
            var file = options.file || self.getFile();
            var currentDate = _options.currentDate || Com.date.getCurrentDate();
            var openAuthInfo = options.openAuthInfo || {};
            var access_token = openAuthInfo.access_token || self.getAccessToken();
            var fileUID = file.uid || self.getUID();

            // must be required the file info, authorize info
            if (!file.size || !access_token) {
                console.log('is not file or access_token.');
                return null;
            }

            options = {
                role: options.role || _options.role,
                // 奇传改为2.0后，请求file时不再传递spath
                // spath: options.spath ||  ( currentDate + '/' + fileUID
                //         + '.' + Com.file.getExt(file.name) ),
                spath: options.spath,
                filesize: file.size,
                filetype: Com.file.getExt(file.name),
                access_token: access_token
            };

            return options;
        },

        /*
        options = {
            url: requestURL, // optional
            data: {
                role: 角色,  // optional
                access_token: 认证, // optional
                filesize: 文件尺寸, // required
                spath: 文件存储路径, // optional
                device_id: 客户端UID // optional
            }
        }
        */
        requestFile: function(options, callback) {
            var self = this;
            var _options = self.options;
            options = options || {};

            var params = {
                url: options.url || _options.requestURL,
                headers: {
                    filetype: Com.file.getExt(options.file.name),
                    filesize: options.file.size,
                    role: options.file.role || _options.role,
                    location: options.file.location || _options.location,
                    producttype: options.file.producttype || _options.producttype,
                    businessType: options.file.businessType || _options.businessType
                }
            };

            var _callback = function(data) {
                if (data && data.code == 'A00000') {
                    callback.call(this, data);
                } else {
                    _options.onError.call(self, data);
                }
                if (_options.onRequest) {
                    _options.onRequest.call(self, data);
                }
            };

            return self.dao.qichuanRequestFile(params, _callback);
        },

        send: function(options, handler) {
            //        var self = this;
            handler = handler || {};
            var $xhr = $.ajax({
                url: options.url,
                processData: false,
                dataType: 'json',
                headers: options.headers,
                contentType: 'application/x-www-form-urlencoded',
                // contentType: false,
                data: options.file,
                method: 'POST',

                beforeSend: function(data) {
                    if (handler.onBeforeSend) {
                        handler.onBeforeSend.call(this, data);
                    }
                },
                success: function(data) {
                    if (handler.onFinish) {
                        handler.onFinish.call(this, data);
                    }
                },
                complete: function(data) {
                    if (handler.onComplete) {
                        handler.onComplete.call(this, data);
                    }
                },
                error: function(data) {
                    if (handler.onError) {
                        handler.onError.call(this, data);
                    }
                }
            });

            return $xhr;
        },



        uploadFile: function(options, callback) {

            var self = this;
            var _options = self.options;
            options = options || {};

            var data = options.data;

            var file = _options.file || self.getFile();
            var params;
            var handler = {
                onFail: _options.onFail,
                onError: _options.onError,
                onProgress: _options.onProgress
            };

            file.file_id = data.file_id;

            params = {
                url: file.upload_url || _options.uploadURL,
                file: file,
                headers: {
                    file_id: file.file_id,
                    file_size: file.size,
                    range: data.range || ('0' + '-' + (file.size - 1) + ''),
                    businessType: _options.businessType
                }
            };

            // 直接上传，完成后回调
            handler.onFinish = function(data) {

                if (!$.isPlainObject(data)) {
                    data = $.parseJSON(data);
                }
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            return self.dao.qichuanUploadFile(params, handler);
        },

        // 一个文件的片段上传完成后，发起结束通知
        finishUpload: function(options, handler) {
            var self = this;
            handler = handler || {};
            options = options || {};
            var _options = self.options;
            var file = options.file || self.getFile();
            var params = null;
            var access_token = options.access_token || self.getAccessToken();
            params = {
                contentType: 'application/json',
                url: options.url,
                headers: {
                    access_token: access_token,
                    file_id: file.file_id,
                    range_finished: 'true'
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onFinish.call(self, data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });
        },

        startUpload: function(options, handler) {
            var self = this;
            var _options = self.options;
            options = options || {};

            handler = options.handler;

            if (options.file) {
                _options.file = options.file;
            }

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onStart.call(self, data);
                    self.uploadFile(data);
                } else {
                    _options.onError.call(self, data);
                }
            };

            self.requestFile(options, callback);

        },

        cancelUpload: function(options) {
            var self = this;
            var _options = self.options;
            handler = handler || {};
            var file = options.file || _options.file;
            var cancelUrl = self.getUploadHost() + '' + _options.cancelUrl;
            var params = {
                url: cancelUrl,
                headers: {
                    // 按照奇传接口定义取消参数
                    access_token: options.access_token || self.getAccessToken(),
                    file_id: file.file_id,
                    status: 2
                }
            };

            var callback = function(data) {
                if (data.code == 'A00000') {
                    _options.onCancel.call(self, data);
                } else {
                    data.errorMsg = 'onCancel error.';
                    _options.onCancel.call(self, data);
                }
            };

            self.send(params, {
                onFinish: callback
            });

        }
    };


});